@file:Suppress("SpellCheckingInspection", "BlockingMethodInNonBlockingContext")

package org.glavo.bot

import org.apache.commons.io.input.Tailer
import org.apache.commons.io.input.TailerListener
import java.io.*
import java.time.Duration
import java.util.concurrent.atomic.AtomicBoolean

private const val delayMillis = 800L

private val logFile = File(System.getenv("MC_LOG_FILE"))

val rebooting = AtomicBoolean(false)

fun monitorServer() {
    val tailer = Tailer.builder()
        .setStartThread(false)
        .setFile(logFile)
        .setTailFromEnd(true)
        .setDelayDuration(Duration.ofMillis(delayMillis))
        //.setReOpen(true)
        .setTailerListener(object : TailerListener {
            override fun init(tailer: Tailer?) {
                bot.logger.info("开始监视服务器日志: $logFile")
            }

            override fun fileNotFound() {
                // bot.logger.warning("日志文件 $logFile 不存在")
            }

            override fun fileRotated() {

            }

            override fun handle(line: String) {
                try {
                    bot.logger.info("[Minecraft] $line")
                    matchLog(line)
                } catch (ex: Throwable) {
                    bot.logger.error("TODO", ex)
                }
            }

            override fun handle(ex: java.lang.Exception?) {
                bot.logger.warning("Minecraft log read failure", ex)
            }

        })
        .get()

    val thread = Thread(tailer, "Minecraft Server Monitor")
    thread.isDaemon = true
    thread.start()
}
